﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeTracker.BusinessObjects.TimeSheet.ComponentParts;

namespace TimeTracker.BusinessObjects.TimeSheet
{
    public class TimeSheet
    {
        #region Properties

        private DateTime _startDate;
        public DateTime StartDate
        {
            get { return _startDate; }
        }

        private DateTime _endDate;
        public DateTime EndDate
        {
            get { return _endDate; }
        }
        
        private IList<WorkDay> _workDays;
        public IList<WorkDay> WorkDays
        {
            get { return _workDays; }
            set { _workDays = value; }
        }

        #endregion

        #region Constructors

        public TimeSheet(DateTime StartDate, int DaysOnTimeSheet)
        {
            if (IsValidDaysOnTimeSheet(DaysOnTimeSheet))
                InitializeTimeSheet(StartDate, DaysOnTimeSheet);
        }

        public TimeSheet(string StartDate, int DaysOnTimeSheet)
        {
            if (IsValidStartDate(StartDate) && IsValidDaysOnTimeSheet(DaysOnTimeSheet))
                InitializeTimeSheet(Convert.ToDateTime(StartDate), DaysOnTimeSheet);
        }

        private bool IsValidDaysOnTimeSheet(int DaysOnTimeSheet)
        {
            if (DaysOnTimeSheet <= 0 || DaysOnTimeSheet > 365)
                throw new ArgumentOutOfRangeException("DaysOnTimeSheet", 
                    "The value must be a value from 1-365");

            return true;
        }

        private bool IsValidStartDate(string StartDate)
        {
            DateTime sd;
            if (!DateTime.TryParse(StartDate, out sd))
                throw new ArgumentException("The value supplied is not a valid date.", "StartDate");

            return true;
        }

        private void InitializeTimeSheet(DateTime StartDate, int DaysOnTimeSheet)
        {
            _startDate = StartDate;
            _endDate = StartDate.AddDays(DaysOnTimeSheet - 1);
            _workDays = new List<WorkDay>();

            TimeSpan ts = _endDate - _startDate;
            for (int i = 0; i < DaysOnTimeSheet; i++)
            {
                _workDays.Add(new WorkDay(_startDate.AddDays(i)));
            }
        }

        #endregion

        #region Methods

        public WorkDay GetWorkDayByDate(DateTime DateOfWorkDay)
        {
            return _workDays.Single(wd => wd.Date.Equals(DateOfWorkDay));
        }

        public WorkDay GetWorkDayByDate(string DateOfWorkDay)
        {
            DateTime dt;

            if (!DateTime.TryParse(DateOfWorkDay, out dt))
                throw new ArgumentException("The value supplied wasn't a valid date", 
                    "DayOfWorkDay");

            return _workDays.Single(wd => wd.Date.Equals(dt));
        }

        #endregion
    }
}
